// let mut runtime = SimpleRuntime::new();
// let mut task1 = &mut async {
//     let u = unsafe { &*usart1 };
//     u.dma_write().await;
//     // (*usart1).dma_write(&mut dma_buf1, 1024);
// } as &mut dyn Future<Output = ()>;
// let task1_static: &'static mut dyn Future<Output = ()> = unsafe { transmute(task1) };
// runtime.spawn(task1_static);
// runtime.run();

use core::{
    future::Future,
    ops::{Deref, DerefMut},
    pin::{pin, Pin},
    ptr,
    sync::atomic::{AtomicBool, AtomicU8},
    task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

use heapless::{spsc::Queue, FnvIndexMap, IndexMap, Vec};
use riscv::interrupt;

pub static mut wakers: heapless::FnvIndexMap<u8, Waker, 16> = heapless::FnvIndexMap::new();

// 克隆函数（当 Waker 被 clone() 时调用）
unsafe fn clone(state: *const ()) -> RawWaker {
    // // 将裸指针转换回 Arc<TaskState>
    // let arc = Arc::from_raw(state as *const TaskState);

    // // 克隆 Arc（增加引用计数）
    // let cloned = arc.clone();

    // // 忘记原始的 Arc，避免被释放
    // Arc::into_raw(arc);

    // // 构建新的 RawWaker
    // RawWaker::new(
    //     Arc::into_raw(cloned) as *const (),
    //     &VTABLE, // 使用全局静态的 VTable
    // )
    RawWaker::new(state, &VTABLE)
}

// 唤醒函数（当调用 Waker.wake() 时触发）
unsafe fn wake(state: *const ()) {
    //获取task_id
    let task_pointer = &*(state as *const Task);
    task_pointer
        .active
        .store(true, core::sync::atomic::Ordering::Relaxed);

    // // 将裸指针转换为 Arc<TaskState>
    // let arc = Arc::from_raw(state as *const TaskState);

    // // 设置唤醒标志
    // arc.is_woken.store(true, Ordering::Relaxed);

    // // 显式释放 Arc（因为 wake() 会消费 Waker）
    // drop(arc);
}

// 借用唤醒函数（当调用 Waker.wake_by_ref() 时触发）
unsafe fn wake_by_ref(state: *const ()) {
    // // 不需要消费 Arc，直接操作
    // let arc = Arc::from_raw(state as *const TaskState);
    // arc.is_woken.store(true, Ordering::Relaxed);

    // // 恢复指针所有权，避免被释放
    // Arc::into_raw(arc);
}

// 释放函数（当 Waker 被 drop 时调用）
unsafe fn drop(state: *const ()) {
    // 将裸指针转换回 Arc 并释放
    // drop(Arc::from_raw(state as *const TaskState));
}

// 定义全局静态的 VTable
static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);

// fn run<F: Future<Output = ()>>(future: F) {
//     // 将 Future 固定到栈上
//     let mut future = pin!(future);

//     // 初始化任务状态
//     let state = TaskState::new();

//     // 循环执行 poll
//     loop {
//         // 创建 Context
//         let cx = &mut create_context(state.clone());

//         // 调用 poll
//         match future.as_mut().poll(cx) {
//             Poll::Ready(_) => break,
//             Poll::Pending => {

//                 // // 检查是否被唤醒
//                 // if !state.is_woken.swap(false, Ordering::Relaxed) {
//                 //     // 如果未被唤醒，主动让出 CPU（实际运行时可能用 epoll 等）
//                 //     thread::yield_now();
//                 // }
//             }
//         }
//     }
// }

pub trait InterruptIdFlag {
    const INTERRUPT_ID: u8;
}

static TASK_ID_COUNTER: AtomicU8 = AtomicU8::new(0);
struct Task<'a> {
    task_id: u8,
    future: Pin<&'a mut dyn Future<Output = ()>>,
    active: AtomicBool,
    runtime_pointer: *const SimpleRuntime<'a>,
}
impl<'a> Task<'a> {
    pub fn new(task_id: u8, future: Pin<&mut dyn Future<Output = ()>>) -> Task {
        Task {
            task_id,
            future,
            active: AtomicBool::new(true),
            runtime_pointer: ptr::null(),
        }
    }
}
pub struct SimpleRuntime<'a> {
    alltasks: heapless::FnvIndexMap<u8, Task<'a>, 10>,
    // active_tasks_id: heapless::FnvIndexMap<u8, u8, 10>,
}

impl<'a> SimpleRuntime<'a> {
    pub fn new() -> SimpleRuntime<'a> {
        SimpleRuntime {
            alltasks: heapless::FnvIndexMap::<u8, Task, 10>::new(),
        }
    }
    pub fn spawn(&mut self, future: &'static mut dyn Future<Output = ()>) {
        let taskid = TASK_ID_COUNTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
        let p = Pin::static_mut(future);

        let task = Task::new(taskid, p);
        self.alltasks.insert(taskid, task);
    }
    pub fn run(&mut self) {
        let mut remove_keys: Vec<u8, 8> = Vec::new();
        loop {
            self.alltasks.iter_mut().for_each(|(_, task)| {
                if task.active.load(core::sync::atomic::Ordering::Acquire) {
                    let raw_waker = RawWaker::new(task as *const Task as *const (), &VTABLE);
                    let waker = unsafe { Waker::from_raw(raw_waker) };
                    let mut ct = Context::from_waker(&waker);
                    match task.future.as_mut().poll(&mut ct) {
                        Poll::Ready(_) => {
                            remove_keys.push(task.task_id);
                        }
                        Poll::Pending => {
                            // 此时已经返回Pending，按理说应将active设为false,如果此刻陷入中断，唤醒了这个task，则就会有问题
                            // 所以此处用原子变量，在active为true时
                            // if let Err(oldval) = task.active.compare_exchange(
                            //     true,
                            //     false,
                            //     core::sync::atomic::Ordering::Acquire,
                            //     core::sync::atomic::Ordering::Relaxed,
                            // ) {}
                        }
                    }
                }
            });
            for item in &remove_keys {
                self.alltasks.remove(item);
            }
        }
    }
}
